# -*- coding: utf-8 -*-
#
# Copyright (c) 2013-2021 Virtual Cable S.L.U.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright notice,
#      this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice,
#      this list of conditions and the following disclaimer in the documentation
#      and/or other materials provided with the distribution.
#    * Neither the name of Virtual Cable S.L.U. nor the names of its contributors
#      may be used to endorse or promote products derived from this software
#      without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


"""
Author: Adolfo Gómez, dkmaster at dkmon dot com
"""
import dataclasses
import datetime
import time
import logging
import typing
import collections.abc

from uds.core.managers.stats import StatsManager, _REVERSE_FLDS_EQUIV
from uds.core import types
from uds.models import Provider, Service, ServicePool, Authenticator, OSManager

logger = logging.getLogger(__name__)

# EventTupleType = tuple[datetime.datetime, str, str, str, str, int]

if typing.TYPE_CHECKING:
    from django.db import models


_OWNER_FROM_MODEL: typing.Final[collections.abc.Mapping[type['models.Model'], types.stats.EventOwnerType]] = {
    ServicePool: types.stats.EventOwnerType.SERVICEPOOL,
    Service: types.stats.EventOwnerType.SERVICE,
    Provider: types.stats.EventOwnerType.PROVIDER,
    Authenticator: types.stats.EventOwnerType.AUTHENTICATOR,
    OSManager: types.stats.EventOwnerType.OSMANAGER,
}

# Events data (fld1, fld2, fld3, fld4):
# types.events.EventType.ET_LOGIN --> on Authenticator
#     (username, srcip)
#   Note: Generated on user login on UDS web
#
# types.events.EventType.ET_PLATFORM --> on Authenticator
#     (platform, browser, version)
#   Note: Generated on user login on UDS web
#
# types.events.EventType.ET_LOGOUT --> on Authenticator
#     (username, srcip)
#   Note: Generated on user logout on UDS web. Not generated if browser is closed or session discards.
#
# types.events.EventType.ET_CACHE_HIT --> On UserService
#     (usableServicesInCacheL1,)
#   Note: Generated on assigning from cache to user
#
# types.events.EventType.ET_CACHE_MISS --> On UserService
#     (preparingServicesInCacheL1,)
#   Note: Generated on missed assigning from cache to user
#
# types.events.EventType.ET_ACCESS -> On ServicePool
#     (username, srcpi, dstip, userService_uuid)
#   Note: Generated on user access to service in UDS (that is, clicked on an service)
#
# types.events.EventType.ET_LOGIN -> On ServicePool
#     (username, knownUserIp, serviceIp, fullUserName)
#   Note: Generated by OsManager (that is, services without os manager will not trigger this)
#
# types.events.EventType.ET_LOGOUT -> On ServicePool
#     (username, knownUserIp, serviceIp, fullUserName)
#   Note: Generated by OsManager (that is, services without os manager will not trigger this)
#
# OT_TUNNEL_OPEN: -> On ServicePool
#     (username, srcip, dstip, tunnel_id)
#   Note: For HTML5, scrip = "source" string indicating tunnel type (HTML5-{RDP,RDP,VNC})
#
# OT_TUNNEL_CLOSE: -> On ServicePool
#     (duration, sent, received, tunnel_id)
#
# OT_OSMANAGER_INIT: -> On OsManager
#     (servicepool_uuid, srcip, userservice_uuid)
#
# OT_OSMANAGER_READY: -> On OsManager
#     (servicepool_uuid, srcip, userservice_uuid)
#
# OT_OSMANAGER_RELEASE: -> On OsManager
#     (servicepool_uuid, '', userservice_uuid)


# Helpers
# get owner by type and id
def get_owner(
    owner_type: types.stats.EventOwnerType, owner_id: int
) -> 'Provider|Service|ServicePool|Authenticator|OSManager|None':
    match owner_type:
        case types.stats.EventOwnerType.PROVIDER:
            return Provider.objects.get(pk=owner_id)
        case types.stats.EventOwnerType.SERVICE:
            return Service.objects.get(pk=owner_id)
        case types.stats.EventOwnerType.SERVICEPOOL:
            return ServicePool.objects.get(pk=owner_id)
        case types.stats.EventOwnerType.AUTHENTICATOR:
            return Authenticator.objects.get(pk=owner_id)
        case types.stats.EventOwnerType.OSMANAGER:
            return OSManager.objects.get(pk=owner_id)

    return None  # Should never happen


@dataclasses.dataclass
class EventTupleType:
    stamp: datetime.datetime
    fld1: str
    fld2: str
    fld3: str
    fld4: str
    event_type: types.stats.EventType

    # aliases for fields
    def __getitem__(self, item: str) -> typing.Any:
        if item in _REVERSE_FLDS_EQUIV:
            item = _REVERSE_FLDS_EQUIV[item]
        return self.__getattribute__(item)

    # Obtains the Event as a string
    def __str__(self) -> str:
        # Convert Event type to string first
        return f'{self.stamp} {self.event_type.event_name} {self.fld1} {self.fld2} {self.fld3} {self.fld4}'


EventClass = typing.Union[Provider, Service, ServicePool, Authenticator]


def add_event(obj: EventClass, event_type: types.stats.EventType, **kwargs: typing.Any) -> bool:
    """
    Adds a event stat to specified object

    Although any counter type can be added to any object, there is a relation that must be observed
    or, otherway, the stats will not be recoverable at all:


    note: Runtime checks are done so if we try to insert an unssuported stat, this won't be inserted and it will be logged
    """

    return StatsManager.manager().add_event(_OWNER_FROM_MODEL[type(obj)], obj.id, event_type, **kwargs)


def get_events(
    obj: EventClass, event_type: types.stats.EventType,
    *,
    since: 'datetime.datetime|int|None' = None,
    to: 'datetime.datetime|int|None' = None,
    limit: int = 0,
    all: bool = False,
) -> typing.Generator[EventTupleType, None, None]:
    """
    Get events

    Args:
        obj: Object to get events from
        event_type: Type of event to get
        since: From when to get events
        to: To when to get events
        limit: Max number of results to get
        all: If True, gets events from all objects of the same type

    Returns:
        A generator, that contains pairs of (stamp, value) tuples
    """
    object_type = type(obj)

    if not all:
        owner_id = None
    else:
        owner_id = obj.pk

    for i in StatsManager.manager().enumerate_events(
        _OWNER_FROM_MODEL[object_type],
        event_type,
        owner_id=owner_id,
        since=since,
        to=to,
        limit=limit,
    ):
        yield EventTupleType(
            datetime.datetime.fromtimestamp(i.stamp),
            i.fld1,
            i.fld2,
            i.fld3,
            i.fld4,
            types.stats.EventType.from_int(i.event_type),
        )


# tail the events table
def tail_events(wait_time: int = 2) -> typing.Generator[EventTupleType, None, None]:
    starting_id = None
    while True:
        for i in StatsManager.manager().tail_events(starting_id=starting_id):
            yield EventTupleType(
                datetime.datetime.fromtimestamp(i.stamp),
                i.fld1,
                i.fld2,
                i.fld3,
                i.fld4,
                types.stats.EventType.from_int(i.event_type),
            )
            starting_id = i.pk if i.pk > (starting_id or 0) else starting_id
        time.sleep(wait_time)
